const request = require('../../utils/request')

Page({

  /**
   * 页面的初始数据
   */
  data: {
    category:null,
    shops:[],//九宫格进来的对应的列表数据
    pageIndex:0,//页码
    pageSize:20,//每页的数据
    totalCount:0,
    hasMore:true,//标记
    searchText:"",
    searchShowed:false,
  },

  loadMore(){
    //解构赋值
    let {pageIndex,pageSize,searchText} = this.data;
    const params = {_page:++pageIndex,_limit:pageSize}
    if(searchText){
      params.q = searchText
    }
    console.log(params)

    return request(`/categories/${this.data.category.id}/shops`,params)
    .then(res=>{
      console.log(res)
      const totalCount = parseInt(res.header['x-total-count']);
      const hasMore = this.data.pageIndex * this.data.pageSize < totalCount;
      const shops = this.data.shops.concat(res.data)
      this.setData({
        shops,
        totalCount,
        pageIndex,
        hasMore
      })
    })

  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    request(`/categories/${options.cat}`)
    .then(res=>{
      // console.log(res.data)
      this.setData({
        category:res.data
      })
      wx.setNavigationBarTitle({
        title: res.data.name
      })

      this.loadMore()
    })
    



  },

 


  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    //页面顶部下拉动作  不是加载后续的数据 应该是刚加进来的数据
    console.log("下拉")
    this.setData({
      shops:[],
      pageIndex:0,
      hasMore:true
    })

    this.loadMore().then(()=> wx.stopPullDownRefresh())
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
   console.log("上拉")
   this.loadMore();
  },
  //搜索功能的实现
  searchHandle(){
    console.log(this.data.searchText)
    this.setData({
      shops:[],
      pageIndex:0,
      hasMore:true
    })

    this.loadMore();
  },

  showSearchHandle(){
   this.setData({
     searchShowed : true
   })
  },

  hideSearchHandle(){
    this.setData({
      searchShowed : false,
      searchText : ''
    })
  },

  clearSearchHandle(){
    this.setData({
      searchText : ''
    })
  },


  searchChangeHandle(e){
   console.log(e)
   this.setData({
    searchText : e.detail.value
  })
  }


})